package bsi.vn.FirstApp;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import bsi.vn.Data.ATMAdapter;
import bsi.vn.Data.ATMData;
import bsi.vn.Data.CookieData;
import bsi.vn.Data.CustomerData;
import bsi.vn.Data.CustomerSpinnerAdapter;
import bsi.vn.Data.ProvinceData;
import bsi.vn.Data.ProvinceSpinnerAdapter;
import bsi.vn.Data.ResultSearchData;
import bsi.vn.Data.ResultSearchSpinnerAdapter;
import bsi.vn.Lib.Consts;
import bsi.vn.Lib.ProcessFunc;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemClickListener;
import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;

public class ATMSearchActivity extends Activity implements OnClickListener {
	private ArrayList<ATMData> ArrATM = new ArrayList<ATMData>();
	Spinner snProvince;
	Spinner snCustomer;
	Spinner snResult;
	private View condition;
	private View result;
	private Button btnDisplaySearch;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_atmsearch);

		condition = findViewById(R.id.asllSearchCondition);
		result = findViewById(R.id.asllResult);
		btnDisplaySearch = (Button) findViewById(R.id.asbtnDisplaySearch);
		btnDisplaySearch.setOnClickListener(this);

		this.getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		snProvince = (Spinner) findViewById(R.id.assnProvince);
		ArrayAdapter<ProvinceData> proAdapter = new ProvinceSpinnerAdapter(
				ATMSearchActivity.this, R.layout.spinner_row,
				ProcessFunc.GetProvince(ATMSearchActivity.this));
		snProvince.setAdapter(proAdapter);

		snCustomer = (Spinner) findViewById(R.id.assnCustomer);
		ArrayAdapter<CustomerData> cusAdapter = new CustomerSpinnerAdapter(
				ATMSearchActivity.this, R.layout.spinner_row,
				ProcessFunc.GetCustomer(ATMSearchActivity.this));
		snCustomer.setAdapter(cusAdapter);

		snResult = (Spinner) findViewById(R.id.assnResult);
		ArrayAdapter<ResultSearchData> resultAdapter = new ResultSearchSpinnerAdapter(
				ATMSearchActivity.this, R.layout.spinner_row,
				ProcessFunc.GetResultSearch(ATMSearchActivity.this));
		snResult.setAdapter(resultAdapter);

		findViewById(R.id.asbtSearch).setOnClickListener(this);
//				new View.OnClickListener() {
//					@Override
//					public void onClick(View view) {
//						condition.setVisibility(view.INVISIBLE);
//						result.setVisibility(view.VISIBLE);
//						// InputMethodManager imm = (InputMethodManager)
//						// getSystemService(
//						// INPUT_METHOD_SERVICE);
//						// imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
//						// 0);
//
//						ProcessFunc.hideSoftKeyboard(ATMSearchActivity.this);
//						myAsyncTask myWebFetch = new myAsyncTask();
//						myWebFetch.execute();
//					}
//				});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.asbtnDisplaySearch:
			condition.setVisibility(View.VISIBLE);
			result.setVisibility(View.INVISIBLE);
			break;
		case R.id.asbtSearch:
			ArrATM.clear();
			ProcessFunc.hideSoftKeyboard(ATMSearchActivity.this);
			condition.setVisibility(View.INVISIBLE);
			result.setVisibility(View.VISIBLE);			
			
			
			
			// InputMethodManager imm = (InputMethodManager)
			// getSystemService(
			// INPUT_METHOD_SERVICE);
			// imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
			// 0);

			
			myAsyncTask myWebFetch = new myAsyncTask();
			myWebFetch.execute();
			break;

		default:
			break;
		}

	}

	private class myAsyncTask extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			String l_sSerialNo = ((EditText) findViewById(R.id.asedSerialNo))
					.getText().toString();
			String l_sAddress = ((EditText) findViewById(R.id.asedAddress))
					.getText().toString();
			ProvinceData l_cProvince = (ProvinceData) ((Spinner) findViewById(R.id.assnProvince))
					.getSelectedItem();
			CustomerData l_cCustomer = (CustomerData) ((Spinner) findViewById(R.id.assnCustomer))
					.getSelectedItem();
			ResultSearchData l_cResult = (ResultSearchData) ((Spinner) findViewById(R.id.assnResult))
					.getSelectedItem();

			return GetATM(l_sSerialNo, l_sAddress, l_cProvince.getId(),
					l_cCustomer.getId(), l_cResult.getId());
		}

		@Override
		protected void onPostExecute(String result) {
			String sResponse[] = result.split("\\|");
			if (Integer.parseInt(sResponse[0]) != 0) {

				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
						ATMSearchActivity.this);
				alertDialogBuilder.setTitle("Notice");
				alertDialogBuilder
						.setMessage(sResponse[1])
						.setCancelable(false)
						.setPositiveButton("OK",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int id) {
										finish();
									}
								});
				AlertDialog alertDialog = alertDialogBuilder.create();
				alertDialog.show();
			} else {
				try {
					JSONArray jArray = new JSONArray(sResponse[1]);
					for (int i = 0; i < jArray.length(); i++) {
						JSONObject json_data = jArray.getJSONObject(i);
						ATMData atm = new ATMData();
						atm.setATMId(json_data.getInt(Consts.SDB_ATMID));
						atm.setSerialNo(json_data
								.getString(Consts.SDB_SERIALNO));
						atm.setProvince(json_data
								.getString(Consts.SDB_PROVINCE));
						atm.setCustomer(json_data
								.getString(Consts.SDB_CUSTOMER));
						ArrATM.add(atm);
					}
				} catch (JSONException e) {
					Log.e("log_tag", "Error parsing data " + e.toString());
				}
			}

			final ListView lv1 = (ListView) findViewById(R.id.aslvATMList);
			lv1.setAdapter(new ATMAdapter(ATMSearchActivity.this, ArrATM));

			lv1.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					int ATMId = ArrATM.get(position).getATMId();
					Intent i = new Intent(getApplicationContext(),
							ATMDetailFragmentActivity.class);
					i.putExtra("ATMId", ATMId);
					startActivity(i);
				}
			});
		}

		@Override
		protected void onPreExecute() {
			// CheckDataValid();
			// showProgress(true);
			// super.onPreExecute();
			// tv.setText("Started Running….");
		}

		@Override
		protected void onProgressUpdate(String... text) {
			// finalResult.setText(text[0]);
			// Things to be done while execution of long running operation is in
			// progress. For example updating ProgessDialog
		}
	}

	private String GetATM(String serialno, String address, int province,
			int customer, int resutl) {
		InputStream is = null;
		String result = "";
		try {
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(Consts.MAIN_URL);

			CookieData cookie = ProcessFunc.GetCookie(ATMSearchActivity.this);

			List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(8);
			nameValuePair.add(new BasicNameValuePair(Consts.V_FUNC,
					Consts.F_ATMLIST));
			nameValuePair.add(new BasicNameValuePair(Consts.V_USERID, String
					.valueOf(cookie.getUserId())));
			nameValuePair.add(new BasicNameValuePair(Consts.V_COOKIE, cookie
					.getCookie()));
			nameValuePair
					.add(new BasicNameValuePair(Consts.V_SERIAL, serialno));
			nameValuePair
					.add(new BasicNameValuePair(Consts.V_ADDRESS, address));
			nameValuePair.add(new BasicNameValuePair(Consts.V_PROVINCE, String
					.valueOf(province)));
			nameValuePair.add(new BasicNameValuePair(Consts.V_CUSTOMER, String
					.valueOf(customer)));
			nameValuePair.add(new BasicNameValuePair(Consts.V_RESULT, String
					.valueOf(result)));

			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "utf-8"), 16);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * Set up the {@link android.app.ActionBar}, if the API is available.
	 */
	// @TargetApi(Build.VERSION_CODES.HONEYCOMB)
	// private void setupActionBar() {
	// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
	// getActionBar().setDisplayHomeAsUpEnabled(true);
	// }
	// }

	// @Override
	// public boolean onCreateOptionsMenu(Menu menu) {
	// // TODO Auto-generated method stub
	// getMenuInflater().inflate(R.menu.atmsearch, menu);
	// return true;
	//
	// }
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.atmsearch, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() != R.id.menu_sub
				&& item.getItemId() != R.id.menu_ATM) {
			startActivity(ProcessFunc.MenuAction(this, item));
		}

		return true;
	}

}
